package com.foreknow.tijian.dao.Impl;

import com.foreknow.tijian.dao.CartDao;
import com.foreknow.tijian.po.Business;
import com.foreknow.tijian.po.Cart;
import com.foreknow.tijian.po.Food;
import com.foreknow.tijian.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartDaoImpl implements CartDao {
    //连接数据库
    Connection con= DBUtil.getConnection();
    PreparedStatement pst;
    @Override
    public List<Cart> listCart(Cart cart) {
        List<Cart> cartList = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT c.*, ");
        stringBuffer.append("f.foodId ffoodId, ");
        stringBuffer.append("f.foodName ffoodName, ");
        stringBuffer.append("f.foodExplain ffoodExplain, ");
        stringBuffer.append("f.foodImg ffoodImg, ");
        stringBuffer.append("f.foodPrice ffoodPrice, ");
        stringBuffer.append("f.businessId fbusinessId, ");
        stringBuffer.append("b.businessId bbusinessId, ");
        stringBuffer.append("b.businessName bbusinesName, ");
        stringBuffer.append("b.businessAddress bbusinessAddress, ");
        stringBuffer.append("b.businessExplain bbusinessExplain, ");
        stringBuffer.append("b.businessImg bbusinessImg, ");
        stringBuffer.append("b.orderTypeId borderTypeId, ");
        stringBuffer.append("b.starPrice bstarPrice, ");
        stringBuffer.append("b.deliveryPrice bdeliveryPrice, ");
        stringBuffer.append("b.remarks bremarks ");
        stringBuffer.append("FROM cart c left JOIN food f ON c.foodId = f.foodId ");
        stringBuffer.append("LEFT JOIN business b ON c.businessId = b.businessId ");
        stringBuffer.append("WHERE c.userId=? ");
        if(cart.getBusinessId()!=null) {
            stringBuffer.append(" AND b.businessId=" +  cart.getBusinessId());
        }
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(stringBuffer.toString());
            pst.setString(1,cart.getUserId());
            ResultSet rs = pst.executeQuery(); //执行查询
            while (rs.next()) {
                Cart cartResult = new Cart();
                cartResult.setCartId(rs.getInt("cartId"));
                cartResult.setFoodId(rs.getInt("foodId"));
                cartResult.setBusinessId(rs.getInt("businessId"));
                cartResult.setUserId(rs.getString("userId"));
                cartResult.setQuantity(rs.getInt("quantity"));
                Food foodResult = new Food();
                foodResult.setFoodId(rs.getInt("ffoodId"));
                foodResult.setFoodName(rs.getString("ffoodName"));
                foodResult.setFoodExplain(rs.getString("ffoodExplain"));
                foodResult.setFoodImg(rs.getString("ffoodImg"));
                foodResult.setFoodPrice(rs.getDouble("ffoodPrice"));
                foodResult.setBusinessId(rs.getInt("businessId"));
                //设置cart与food和business的关联关系
                cartResult.setFood(foodResult);
                Business businessResult = new Business();
                businessResult.setBusinessId(rs.getInt("bbusinessId"));
                businessResult.setBusinessName(rs.getString("bbusinesName"));
                businessResult.setBusinessAddress(rs.getString("bbusinessAddress"));
                businessResult.setBusinessExplain(rs.getString("bbusinessExplain"));
                businessResult.setBusinessImg(rs.getString("bbusinessImg"));
                businessResult.setOrderTypeId(rs.getInt("borderTypeId"));
                businessResult.setStarPrice(rs.getDouble("bstarPrice"));
                businessResult.setDeliveryPrice(rs.getDouble("bdeliveryPrice"));
                businessResult.setRemarks(rs.getString("bremarks"));
                cartResult.setBusiness(businessResult);
                //将Cart对象添加到list集合中
                cartList.add(cartResult);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(pst);
        }
        return cartList;
    }



    @Override
    public int saveCart(String userId, int businessId, int foodId) {
        String sql="insert into cart(foodId,userId,businessId,quantity) values(?,?,?,1)";
        int result=0;
        try{
            DBUtil.getConnection();
            pst=con.prepareStatement(sql);
            pst.setInt(1, foodId);
            pst.setString(2, userId);
            pst.setInt(3, businessId);
            result=pst.executeUpdate();

        } catch (SQLException e) {
            try{
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
          DBUtil.close(pst);
        }
        return result;
    }

    @Override
    public int updateCart(Cart cart) {
        int quantity=cart.getQuantity();
        int foodId=cart.getFoodId();
        int businessId=cart.getBusinessId();
        String userId=cart.getUserId();
        String sql="update cart set quantity=? where userId=? and businessId=? and foodId=?";
        int result=0;
        try{
           pst=con.prepareStatement(sql);
           pst.setInt(1, quantity);
           pst.setString(2, userId);
           pst.setInt(3, businessId);
           pst.setInt(4, foodId);
           result=pst.executeUpdate();
        } catch (SQLException e) {
            try{
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        finally {
            DBUtil.close(pst);
        }
        return result;
    }

    @Override
    public int removeCart(Cart cart) {
        StringBuffer sql =
                new StringBuffer("DELETE FROM cart WHERE userId=? AND businessId=?");
        if(cart.getFoodId() != null && cart.getFoodId()>0){
            sql.append(" AND foodId=" + cart.getFoodId());
        }
        int result = 0;
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql.toString());
            pst.setString(1, cart.getUserId());
            pst.setInt(2, cart.getBusinessId());
            result = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(pst);
        }
        return result;
    }

}
